package de.tu_darmstadt.gdi1.battleship.controller;

import java.text.MessageFormat;

import de.tu_darmstadt.gdi1.battleship.exceptions.FieldAlreadyShotException;
import de.tu_darmstadt.gdi1.battleship.exceptions.InternalFailureException;
import de.tu_darmstadt.gdi1.battleship.exceptions.InvalidCoordinatesException;
import de.tu_darmstadt.gdi1.battleship.model.BattleshipGame;
import de.tu_darmstadt.gdi1.battleship.net.BattleshipServer;
import de.tu_darmstadt.gdi1.battleship.net.NetObject;
import de.tu_darmstadt.gdi1.battleship.view.Messages;
import de.tu_darmstadt.gdi1.battleship.view.StudentWindow;

public class NetworkServerInteraction extends UserInteraction{


	//network
	private BattleshipServer netServer = new BattleshipServer();
	Thread pollingThread;



	public NetworkServerInteraction(BattleshipGame battleshipGame, StudentWindow wnd) {
		super(battleshipGame, wnd);
		netServer.init();
		NetObject obj = new NetObject(getGameString(), bsg.getTurn());	
		netServer.sendObject(obj);
		try {
			mainWnd.setVisible(true);
			mainWnd.getGamePanel().redraw();
		} catch (InternalFailureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		pollingThread = new Thread() {
			boolean active = true;
			
			public void end() {
				active = false;
			}
			
			public void run() {
				NetObject no;
				while(active) {
					if(netServer.getConnection().isClosed()) {
						netServer.close();
						netServer.init();
					} else {
						no = new NetObject(getGameString(), bsg.getTurn());
						netServer.sendObject(no);
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							System.out.println("Polling-Thread failed.");
							e.printStackTrace();
						}
					}

				}
			}
		};
		pollingThread.start();
	}


	public void userClicked(int posX, int posY) {

		if(bsg.getTurn())
		{
			playerShotClick(posX, posY);
			try {
				mainWnd.getGamePanel().redraw();
			} catch (InternalFailureException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			//			
			//			NetObject obj = new NetObject(getGameString(), bsg.getTurn());
			//			netServer.sendObject(obj);
			//			NetObject no = netServer.recieveObject();
			//			while (no.getCorrupt()){
			//			obj = new NetObject(getGameString(), bsg.getTurn());
			//			netServer.sendObject(obj);
			//			no = netServer.recieveObject();}
		}

		// If game has ended notify Player and stop.
		if (bsg.isFinished()) {
			notifyGameWon();
		}
		//		    new Thread(){
		//		    	public void run(){
	
		NetObject  no = netServer.recieveObject();
		try {
			bsg.getHumanMap().shootAt(no.getPos()/10, no.getPos()%10);
			mainWnd.getGamePanel().redraw();
		} catch (InvalidCoordinatesException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FieldAlreadyShotException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InternalFailureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		bsg.setTurn(true);
		NetObject 	 obj = new NetObject(getGameString(), bsg.getTurn());	
		netServer.sendObject(obj);	
		
//		pollingThread.notify();

		//		    	}
	//		    }.start();


	}
	
	public Thread getPollingThread() {
		return pollingThread;
	}

	public void notifyGameWon(){
		Object[] args = { bsg.getPlayerName(),
				new Integer(bsg.getShotsUsed()) };
		MessageFormat formatter = new MessageFormat("");
		formatter.applyPattern(Messages.getString("Info.won"));
		mainWnd.showMessage(formatter.format(args));
	}


	public void notifyGameLost(){
		Object[] args = { bsg.getPlayerName(),
				new Integer(bsg.getShotsUsed()) };
		MessageFormat formatter = new MessageFormat("");
		formatter.applyPattern(Messages.getString("Info.lost"));
		mainWnd.showMessage(formatter.format(args));
	}	


	public String getGameString() {
		if (bsg.getHumanMap() == null || bsg.getCpuMap() == null)
			return "";

		StringBuffer sb = new StringBuffer();

		for (int y = 0; y < 10; y++) {
			for (int x = 0; x < 10; x++) {
				sb.append(bsg.getCpuMap().getEntry(x, y).getSymbol());
			}
			sb.append('|');
			for (int x = 0; x < 10; x++) {
				sb.append(bsg.getHumanMap().getEntry(x, y).getSymbol());
			}
			sb.append('\n');
		}
		return sb.toString();
	}
}
